package users

import (
	"context"
	"errors"
	"product/common/datetime"
	"product/common/encryption"
	"product/common/toolbox"
	"product/common/validator"

	"github.com/zeromicro/go-zero/core/logx"
	"product/authorization/serve/internal/svc"
	"product/authorization/serve/internal/types"
)

type UpdateUsersLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewUpdateUsersLogic update users
func NewUpdateUsersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUsersLogic {
	return &UpdateUsersLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateUsersLogic) UpdateUsers(req *types.UpdateUserReq) (resp *types.UpdateUserResp, err error) {
	ok, fields, err := validUpdateUsersInput(req)
	if !ok && err != nil {
		return &types.UpdateUserResp{
			Ok: false,
		}, nil
	}
	if len(fields) <= 0 {
		return &types.UpdateUserResp{Ok: false}, nil
	}
	ok, err = l.svcCtx.UsersModel.ModifyUserInfo(l.ctx, fields, req.ID)
	if err != nil && !ok {
		return &types.UpdateUserResp{Ok: false}, nil
	}
	return &types.UpdateUserResp{Ok: ok}, nil
}

// 验证更新用户输入
func validUpdateUsersInput(req *types.UpdateUserReq) (bool, map[string]interface{}, error) {
	if req.ID <= 0 {
		return false, nil, errors.New("用户id不能为空")
	}
	updateFields := make(map[string]interface{})
	if !validator.IsEmptyString(req.Email) && validator.IsEmail(req.Email) {
		updateFields["Email"] = req.Email
	}

	if !validator.IsEmptyString(req.Mobile) && validator.IsChineseMobile(req.Mobile) {
		updateFields["Mobile"] = req.Mobile
	}

	if !validator.IsEmptyString(req.Password) && validator.IsStrongPassword(req.Password, 8) {
		salt := toolbox.RandomStringToUpper(8,
			3, true)
		pwdTmp := encryption.Md5WithSalt(req.Password, salt)
		updateFields["PassWord"] = pwdTmp
		updateFields["PasswordSalt"] = salt
	}

	if !validator.IsEmptyString(req.FullName) {
		updateFields["FullName"] = req.FullName
	}

	if !validator.IsEmptyString(req.UserName) {
		updateFields["UserName"] = req.UserName
	}

	if req.TenantID > 0 {
		updateFields["TenantId"] = req.TenantID
	}

	if req.Status > 0 {
		updateFields["Status"] = req.Status
	}
	if len(updateFields) > 0 {
		updateFields["UpdatedAt"] = datetime.GetNowTimestamp()
	}

	return true, updateFields, nil
}
